package com.codingapi.auto.deploy.client;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.List;

/**
 * @author modificial
 * @date 2018/7/23
 * @company codingApi
 * @description SSH连接客户端
 */
public class SSHClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(SSHClient.class);

    /**
     * 执行shell脚本
     *
     * @param host     服务器地址
     * @param port     端口号
     * @param user     用户名
     * @param password 密码
     * @param command  执行的命令
     * @return 结果信息
     */
    public static List<String> exeCommand(String host, int port, String user, String password, String command) {
        JSch jSch = new JSch();
        List<String> out = null;
        Session session = null;
        ChannelExec channelExec = null;
        try {
            session = jSch.getSession(user, host, port);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect(2000);
            channelExec = (ChannelExec) session.openChannel("exec");
            InputStream in = channelExec.getInputStream();
            channelExec.setCommand(command);
            channelExec.setErrStream(System.err);
            channelExec.connect(10000);
            LOGGER.info("连接成功");
            out = IOUtils.readLines(in, "UTF-8");
        } catch (Exception e) {
            LOGGER.error("执行命令失败");
            throw new RuntimeException("执行命令失败");
        } finally {
            assert channelExec != null;
            channelExec.disconnect();
            session.disconnect();
            LOGGER.info("连接关闭成功");
        }
        return out;
    }
}
